package com.qf.anno.web.interceptors;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.qf.anno.domain.Code;
import com.qf.anno.domain.R;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //判断是否登录，如果没有登录，应该拦截
        Object userInfo = request.getSession().getAttribute("userInfo");
        if (userInfo == null){
            //没有登录，应该拦截
            R r = R.error("尚未登录", Code.NO_LOGIN);
            String rJson = new ObjectMapper().writeValueAsString(r);

            //解决响应中文乱码
            response.setContentType("application/json;charset=utf-8");

            response.getWriter().write(rJson);
            return false;
        }

        return true;
    }
}
